<template>
  <div v-if="showdata" class="waybillEdit">
    <!-- class="tab-container waybill-tab-container tab-fixed" -->
    <div style="position: fixed;z-index: 11; top: 20px; left: 100px;">
      <span style="font-size:16px;">{{ waybillData.waybillNo }}</span>
      <el-tooltip effect="light" content="点击复制" placement="bottom">
        <i
          class="el-icon-copy-document tag-read margin-left-xs"
          :data-clipboard-text="waybillData.waybillNo"
          @click="copy"
        ></i>
      </el-tooltip>
      <el-tag
        v-if="activeName === 'receivable'"
        size="small"
        type="danger"
        effect="dark"
        class="pointer"
        @click="sign"
        >标记分配单号</el-tag
      >
      <div
        style="position: fixed;z-index: 11; top: 10px; left: 270px;"
        v-if="showWaybillDetails"
      >
        <HeaderInfo
          :verifyShow="verifyShow"
          :Constatvariable="waybillData"
          :initOptionsData.sync="initOptionsData"
          :pageType.sync="pageType"
          :singleOptions.sync="singleOptions"
        ></HeaderInfo>
      </div>
    </div>
    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="运单编辑" name="edit" class="tabPane">
          <keep-alive>
            <div class="padding">
              <!-- <el-button @click="toPage">toPage</el-button> -->
              <ProgressBar
                class="progressBar"
                ref="bar"
                @saveStateLine="saveStateLine"
                :waybillInfo="waybillData"
                @addFlowNodeAnomaly="addFlowNodeAnomaly"
                @fixAnomalyNode="fixAnomalyNode"
                :allFlowNodeAnomalyMap="allFlowNodeAnomalyMap"
                :waybillAnomalyNodeMap="waybillAnomalyNodeMap"
                :waybillAnomalyNodeIdsMap="waybillAnomalyNodeIdsMap"
                :flowNodeAnomalyMap="flowNodeAnomalyMap"
                :userMap="userMap"
              ></ProgressBar>
              <BasicInfo
                :pageType="pageType"
                :waybillData="waybillData"
                :initOptionsData.sync="initOptionsData"
                :whetherSynchronize="whetherSynchronize"
              ></BasicInfo>
              <WaybillInfo
                :pageType="pageType"
                :tableData.sync="tableInfo"
              ></WaybillInfo>
              <el-dialog :visible.sync="dialogVisible" width="50%" :append-to-body="true"  :before-close="handleClose">
                <template >
                  <span >更改离港&到港原因备注:</span>
                  <el-input type="textarea"  :rows="10" v-model="updateRemark"></el-input>
                </template>
                <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUpdateRemark">确定</el-button>
      </span>
              </el-dialog>
              <GoodsInfo
                :goodsData="goodsData"
                v-if="pageType == 'seaFreight'"
              ></GoodsInfo>

              <MasterOrder
                v-if="!verifyShow.saler || verifyShow.superAdmin"
                :pageType="pageType"
                :waybillData="waybillData"
                :singleOptions="singleOptions"
              ></MasterOrder>
              <el-row>
                <el-col :span="4"></el-col>
                <el-col :span="20">
                  <el-checkbox
                    v-model="whetherSynchronize"
                    style="margin-left: 300px"
                    @change="whetherSynchronizeClick"
                    >最终收件人(系统不同步清关服务商)</el-checkbox
                  >
                </el-col>
              </el-row>
              <HouseOrder
                v-if="
                  (!verifyShow.saler || verifyShow.superAdmin) &&
                    pageType == 'seaFreight'
                "
                :waybillData="waybillData"
              ></HouseOrder>
              <Ams
                v-if="
                  (!verifyShow.saler || verifyShow.superAdmin) &&
                    pageType == 'seaFreight'
                "
                :waybillData="waybillData"
                :restaurants="restaurants"
              >
              </Ams>

              <Isf :restaurants="restaurants" :waybillData="waybillData" v-if="
                    pageType == 'seaFreight'
                "></Isf>
              <!-- 分单H单信息 -->
              <div v-if="simpleWaybillQuerySingleMap && initOptionsData">
                <div
                  v-for="(item, k, i) in simpleWaybillQuerySingleMap"
                  :key="k"
                >
                  <SingleHouseBill
                    :waybillSingleId="parseInt(k)"
                    :initOptionsData.sync="initOptionsData"
                    :restaurants.sync="initOptionsData.serviceCompanyMap"
                    :simpleWaybillForEditWaybillMergeAlls="
                      simpleWaybillForEditWaybillMergeAlls
                    "
                    :index="i + 1"
                    :waybillData="simpleWaybillQuerySingleMap[k]"
                    :pageType="pageType"
                  ></SingleHouseBill>
                </div>
              </div>
            </div>
          </keep-alive>
        </el-tab-pane>
        <el-tab-pane label="文件列表" name="fileList" lazy>
          <FileList
            :isAllocat="true"
            :Constatvariable="waybillData"
            :verifyShow="verifyShow"
          ></FileList>
        </el-tab-pane>
        <el-tab-pane label="应收应付" name="receivable" lazy>
          <Receivable
            ref="receivable"
            :verifyShow="verifyShow"
            :Constatvariable="waybillData"
            :initOptionsData.sync="initOptionsData"
            :waybillInfo="tableInfo"
          ></Receivable>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
import { m } from "@/store/yg/common/local";
import { ajax } from "@/store/yg/common/utils";
import Clipboard from "clipboard";
import FileList from "./../alledit/components/FileList";
import BasicInfo from "./components/BasicInfo";
import WaybillInfo from "./components/WaybillInfo";
import SingleHouseBill from "./components/SingleHouseBill";
import MasterOrder from "./components/MasterOrder";
import HouseOrder from "./components/HouseOrder";
import GoodsInfo from "./components/GoodsInfo";
import HouseBill from "./components/HouseBill";
import Ams from "./components/AMS";
import Isf from "./components/ISF";
import Receivable from "./components/Receivable";
import HeaderInfo from "./components/HeaderInfo";

const ProgressBar = () => import("@/components/app/components/ProgressBar");

export default {
  components: {
    ProgressBar,
    FileList,
    BasicInfo,
    WaybillInfo,
    SingleHouseBill,
    GoodsInfo,
    MasterOrder,
    HouseOrder,
    Receivable,
    HeaderInfo,
    Ams,
    Isf
  },
  props: [],
  data() {
    return {
      updateRemark:"",
      dialogVisible: false,
      waybillSingleId: 0,
      verifyShow: {
        //运单详情
        waybillView: true,
        //提单详情
        pickUpView: true,
        //发票
        invoiceView: true,
        //阿米巴
        amoebaView: true,
        //文件列表
        fileView: true,
        //应付应收
        payAndReceView: true,
        //应付
        payView: true,
        //应收
        receView: true,
        // 是否是跟单操作
        documentaryOperte: false,
        // ​是否是财务
        finace: false,
        // ​​是否是总部财务
        hqFinace: false,
        // ​​是否是HRA
        hra: false,
        // ​​其他
        other: false,
        // ​​是否是海外操作
        overseasOperte: false,
        // ​​是否是销售助理
        saleAssistant: false,
        // ​​是否是销售
        saler: false,
        // ​​是否是客服
        seller: false,
        // ​​是否是物流操作
        shippingOperte: false,
        // ​​是否是超级管理员
        superAdmin: false,
        // ​用户类型 一个用户有多种类型
        userTypes: [],
        // 删除文件
        deleteFile: false,
        // 上传文件
        uploadFile: false,
        // 下载文件
        downloadFile: false,
        // 推送文件
        pushFile: false,
        // 入库单数据
        instock: false,
        // 编辑阿米巴费用
        editAmoeba: false,
        // 删除阿米巴费用
        deleteAmoeba: false
      },
      simpleWaybillQuerySingleMap: {},
      waybillSingleIdCountMap: {},
      simpleWaybillForEditWaybillMergeAlls: {},
      showdata: false,
      waybillId: "",
      shippingway: "",
      allFlowNodeAnomalyMap: {},
      waybillAnomalyNodeMap: {},
      waybillAnomalyNodeIdsMap: {},
      flowNodeAnomalyMap: {},
      userMap: {},
      waybillData: {
        whetherSynchronize: false
      },
      whetherSynchronize: false,
      //下拉 值
      singleOptions: {},
      saveDataParams:{},
      initOptionsData: {},
      configPortMap: {},
      pageType: "airFreight",
      showWaybillDetails: false,
      activeName: "edit",
      countryMap: {},
      serviceItemMap: {},
      channelInfo: {},
      tableInfo: [
        {
          operationId: "sam",
          salesmanId: "sam",
          waybillSingleId: "122121212",
          waybillNo: "121212121",
          isTaxFarming: "1",
          isCustomerDeclaration: "1",
          isVatAndEori: "1",
          eoriIsCertified: "1",
          dispatchAddressCode: "21341234",
          declareNameCn: "士大夫",
          inStockTotalPackages: 1212,
          inStockActualWeight: 123,
          inStockVolume: 123.3,
          waybillLabel: "tag",
          zipCode: "121222"
        }
      ],
      goodsData: [
        { boxType: "柜型" },
        { contairNumber: "柜号" },
        { sealNumber: "封条号" },
        { boxCount: "件数" },
        { packageType: "包装类型" },
        { grossWeight: "毛重" },
        { grossVolume: "体积" }
      ],
      restaurants:{}
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    var head =
      document.head ||
      document.getElementsByTagName("head")[0] ||
      document.documentElement;
    var baseUrl = head.baseURI;
    if (
      null != baseUrl &&
      baseUrl != "" &&
      baseUrl.indexOf("waybill__seafreightmerge__main") != -1
    ) {
      this.pageType = "seaFreight";
    }
    let tabName = sessionStorage.getItem("currentTab");
    //判断是否存在currentTab,即tab页之前是否被点击切换到别的页面
    if (tabName) {
      this.activeName = tabName;
    }
    this.waybillId = this.$route.query.waybillId;
    this.shippingway = this.$route.query.shippingway;
    var activeNameTab = this.$route.query.activeName;
    this.showTabByActive(activeNameTab);
    console.info(this.waybillId, this.shippingway);
    this.initWayBillData();
    this.initOptions();
    this.loadAll()
  },

  destroyed() {
    sessionStorage.removeItem("currentTab");
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});

    },
    whetherSynchronizeClick() {
      this.waybillId = this.$route.query.waybillId;
      var params = this.channelInfo;
      params["id"] = this.waybillId;
      params["whetherSynchronize"] = this.whetherSynchronize;
      const attrs = {
        class: "com.tofba.app.client.seaair.SeaAirWaybillMergeEditClient"
      };
      ajax("updateWhetherSynchronize", params, attrs).then(res => {
        if (res.code != 200) {
          if (null != res.message) {
            this.$message.error(m(res.message));
          } else {
            this.$message.error("修改失败!");
          }
          if (this.whetherSynchronize) {
            this.whetherSynchronize = false;
          } else {
            this.whetherSynchronize = true;
          }
        } else {
          this.$message.success("修改成功!");
        }
      });
    },
    sign() {
      console.log("this.$refs.receivable :>> ", this.$refs.receivable);
      this.$refs.receivable.sign();
    },
    copy() {
      var clipboard = new Clipboard(".tag-read");
      clipboard.on("success", e => {
        this.$message.success("复制成功");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", e => {
        // 不支持复制
        this.$message.error("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },
    async addFlowNodeAnomaly(params){
      console.log("params", params);
      params.waybillId = this.waybillId;
      const data = await ajax("addFlowNodeAnomaly", params);
      if (data.code === 200) {
        this.initWayBillData();
      } else {
        if(data.message) {
          this.$message.error(data.message);
        }
      }
    },
    async fixAnomalyNode(id){
      const data = await ajax("fixAnomalyNode", {id:id});
      if (data.code === 200) {
        this.$message.success("提交解决成功");
        this.initWayBillData();
      } else {
        this.$message.error("提交解决失败");
      }
    },
    async initOptions() {
      var param = {};
      param["id"] = this.waybillId;
      const initData = await ajax("getAllOptions", param);
      if (initData) {
        this.initOptionsData = initData.data;
        this.allFlowNodeAnomalyMap = initData.data["allFlowNodeAnomalyMap"];
        if (this.pageType == "seaFreight") {
          this.configPortMap = this.initOptionsData.configPortMap;
        } else {
          this.configPortMap = this.initOptionsData.airPortMap;
        }
        this.showWaybillDetails = true;
      } else {
        console.log("查询下拉接口出错 请检查接口");
      }
    },
    handleClick(tab) {
      // 点击tab后触发事件，修改显示页面
      sessionStorage.setItem("currentTab", tab.name);
    },
    showTabByActive(activeNameTab) {
      if (null != activeNameTab && activeNameTab != "") {
        this.activeName = activeNameTab;
      }
    },
    async init() {
      const { countryMap } = await initData();
      const { data } = await initAbroadWaybillRender();

      this.countryMap = countryMap;
      this.serviceItemMap = data.serviceItemMap;
    },
    initWayBillData() {
      var param = {};
      ajax("verifyPermissions", param).then(
        res => {
          console.log("海运末端全编辑校验权限", res);
          this.verifyShow = res;
        },
        error => {
          console.log(error);
        }
      );
      param["id"] = this.waybillId;
      param["shippingWayType"] = this.shippingway;
      ajax("editWaybillMergeAll", param).then(
        res => {
          if (res.code != 200) {
            this.$message.error(res.message);
          } else {
            this.waybillData = res.data;
            this.waybillData["netAddress"] = res.data2["netAddress"];
            this.waybillAnomalyNodeMap= res.data2["waybillAnomalyNodeMap"];
            this.waybillAnomalyNodeIdsMap= res.data2["waybillAnomalyNodeIdsMap"];
            this.flowNodeAnomalyMap= res.data2["flowNodeAnomalyMap"];
            this.userMap = res.data2["userMap"];
            var whetherSynchroniz = this.waybillData.whetherSynchronize;
            console.log("是否同步", whetherSynchroniz);
            this.whetherSynchronize = res.data.whetherSynchronize;
            if (this.waybillData.waybillNo) {
              document.title = this.waybillData.waybillNo;
            }
            if (null != res.data2) {
              this.singleOptions = res.data2["singleOptions"];
              this.simpleWaybillQuerySingleMap =
                res.data2["simpleWaybillQuerySingleMap"];
              this.simpleWaybillForEditWaybillMergeAlls =
                res.data2["simpleWaybillForEditWaybillMergeAlls"];
              this.waybillSingleIdCountMap =
                res.data2["waybillSingleIdCountMap"];
            }
          }
          this.showdata = true;
        },
        error => {
          console.log(error);
        }
      );
    },
    saveUpdateRemark(){
      this.saveDataParams.updateRemark=this.updateRemark;
      this.saveData(this.saveDataParams)
      this.dialogVisible=false
    },
    async saveStateLine(params) {
      //保存轨迹节点
      console.log("params", params);
      console.log("waybillData", this.waybillData);
      console.log("operationDateTime",this.waybillData.arrivalPortTime)
      params.waybillId = this.waybillData.id;
      this.saveDataParams=params;
      params.time = params.operationDateTime;
      params.clickStatus = params.status;
      console.log("params2", params);
      //到港时间
      //arrivalPortTime
      //离港时间
      //leavePortTime
      //判断是否是修改了离港
       if (params.clickStatus==80){
         //比较离港修改前的时间和修改后的时间是否一样
         if (this.waybillData.leavePortTime!=params.time){
           //不相同则弹窗
          this.dialogVisible=true
         }else{
           this.saveData(params)
         }
       }else if (params.clickStatus==90){
         if (this.waybillData.arrivalPortTime!=params.time){
           this.dialogVisible=true
         }else{
           this.saveData(params)
         }
       }else{
         this.saveData(params)
       }

    },
    async saveData(params){
      const data = await ajax("updateWaybillStateAndTime", params);
      if (data.code === 200) {
        this.initWayBillData();
      } else {
        this.$message.error(data.failTips);
      }
    },
    loadAll() {
      ajax("getOptionsByparam", { type: "shippingParty" }).then(
        res => {
          console.log("获取申报信息" + res.data);
          if (res.code != 200) {
            this.$message.error(res.message);
          } else {
            if (null != res.data) {
              this.restaurants = res.data;
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.title-icon {
  display: inline-block;
  width: 120px;
}
</style>
<style scoped>
/deep/ .el-tabs__item.is-disabled {
  color: #51abd1;
}

/deep/ .el-form-item__content {
  font-size: 12px;
}

/deep/ .el-autocomplete {
  width: 100%;
}
</style>
